package cn.com.zetatech.maple.core.resource;

import cn.com.zetatech.maple.core.utils.ConfigurationManager;
import cn.com.zetatech.maple.entity.FtpDFile;
import cn.com.zetatech.maple.ftp.FTPUtil;
import com.google.common.base.Joiner;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.net.ftp.FTPClient;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author cheng.cao@zetatech.com.cn
 */
@Slf4j
public class FtpLoader {

    private static final DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyyMMdd");

    public static List<FtpDFile> load() throws Exception {
        String MAPLE_HOME = System.getProperty("MAPLE_HOME");
        String host = ConfigurationManager.me().getString("ftp.server");
        Integer port = ConfigurationManager.me().getInt("ftp.port", 21);
        String username = ConfigurationManager.me().getString("ftp.username");
        String password = ConfigurationManager.me().getString("ftp.password");
        String encoding = ConfigurationManager.me().getString("ftp.encoding");
        String dirPattern = ConfigurationManager.me().getString("ftp.dir-pattern");
        String rootDir = ConfigurationManager.me().getString("ftp.log-base-dir");
        String workspace = ConfigurationManager.me().getString("system.workspace", MAPLE_HOME + "/workspace");

        // 1.系统变量（主要是为了补数据） -> 2.配置文件 -> 默认
        String filePattern = System.getProperty("system.file.date");
        if (StringUtils.isBlank(filePattern)) {
            filePattern = ConfigurationManager.me().getString("system.file.date");
        }
        if (StringUtils.isBlank(filePattern)) {
            filePattern = LocalDate.now().minusDays(1).format(fmt);
        }
        log.info("拉取文件的日期为:{}", filePattern);

        filePattern = String.format("(\\S+)?%s(\\S+)?\\.\\S+", filePattern);
        log.info("日志文件正则表达式:{}", filePattern);
        log.info("下载日志文件开始");
        long start = System.currentTimeMillis();
        FTPClient client = null;
        try {
            client = FTPUtil.connect(host, port, username, password, encoding);
            List<FtpDFile> ftpDFiles = FTPUtil.download(client, rootDir, dirPattern, filePattern, workspace);
            long end = System.currentTimeMillis();
            long stopwatch = end - start;
            if (ftpDFiles.size() == 0) {
                log.error("下载日志文件完成! 日志文件个数: {}, 耗时: {} ms", ftpDFiles.size(), stopwatch);
            } else {
                List<FtpDFile> filedDFiles = ftpDFiles.stream().filter(f -> !f.isSuccess()).collect(Collectors.toList());
                if (filedDFiles.size() == 0) {
                    log.info("下载日志文件完成! 日志文件个数: {}, 下载成功个数: {}, 耗时: {} ms", ftpDFiles.size(), ftpDFiles.size(), stopwatch);
                } else if (filedDFiles.size() < ftpDFiles.size()) {
                    log.warn("下载日志文件完成! 日志文件个数: {}, 下载失败个数: {}, 耗时: {} ms, 下载失败的文件如下：\r\n{}",
                            ftpDFiles.size(), filedDFiles.size(), stopwatch, Joiner.on(",").join(filedDFiles));
                } else {
                    log.error("下载日志文件完成! 日志文件个数: {}, 下载失败个数: {}, 耗时: {} ms, 下载失败的文件如下：\r\n{}",
                            ftpDFiles.size(), filedDFiles.size(), stopwatch, Joiner.on(",").join(filedDFiles));
                }
            }
            return ftpDFiles;
        } catch (Exception e) {
            log.info("下载日志文件异常", e);
            throw e;
        } finally {
            FTPUtil.close(client);
        }
    }
}
